import { authMiddleware } from '@/lib/api';
import { queryPath, queryPostNewInfo } from '@/services/api';
import { cookies } from 'next/headers';
import ResetPage from '@/app/[locale]/reset/reset';
import type { Metadata as MetadataNext } from 'next';
import { createError, customException, getMetadata } from '@/lib/tool';
import type { IPath, IPostEditInfo } from '@/interfaces';
import ContentType from '@/app/[locale]/posts/[id]/edit/content-type/content-type';
import { getTranslator } from 'next-intl/server';

export async function generateMetadata({
  params: { locale },
}: {
  params: {
    locale: string;
  };
}): Promise<MetadataNext> {
  const t = await getTranslator(locale);
  return getMetadata({ title: t('postEditPage.createPost') });
}

async function getData() {
  try {
    const token = authMiddleware(cookies());
    const req1 = queryPath({
      baseURL: process.env.APP_API_SERVER,
      token,
      query: {
        name: '/',
      },
    });
    const req2 = queryPostNewInfo({
      baseURL: process.env.APP_API_SERVER,
      token,
    });

    const responses = await Promise.all([req1, req2]);
    const resp1 = await ((await responses[0]) as Response).json();
    const resp2 = await ((await responses[1]) as Response).json();

    return {
      isSuccess: true,
      isError: false,
      path: resp1.data as IPath,
      info: resp2.data as IPostEditInfo,
    };
  } catch (e: any) {
    return {
      isSuccess: false,
      isError: true,
      error: e,
    };
  }
}

export default async function Page({
  params: { locale },
  searchParams = {},
}: {
  params: { locale: string };
  searchParams: { v?: 'h5' };
}) {
  const data = await getData();
  if (data.isError) {
    return <ResetPage error={createError(data.error)} />;
  }

  const t = await getTranslator(locale);
  const path = data.path!;
  const info = data.info!;

  if (!path.user) {
    return (
      <ResetPage
        error={createError(
          customException(401, t('clientPage.unauthorizedValue')),
        )}
      />
    );
  }

  return (
    <ContentType
      source={info}
      translatedFields={{
        update: t('postEditPage.contentTypePage.update'),
        default: t('postEditPage.contentTypePage.default'),
        link: t('postEditPage.contentTypePage.link'),
        none: t('postEditPage.contentTypePage.none'),
        contentTypePlaceholder: t(
          'postEditPage.contentTypePage.contentTypePlaceholder',
        ),
        contentLinkPlaceholder: t(
          'postEditPage.contentTypePage.contentLinkPlaceholder',
        ),
        nonePlaceholder: t('postEditPage.contentTypePage.nonePlaceholder'),
        updateCompleted: t('postEditPage.contentTypePage.updateCompleted'),
      }}
    />
  );
}
